package com.news.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.news.common.CommonEnum;
import com.news.common.ResponseBean;
import com.news.common.ResultUtil;
import com.news.common.ToolsUtils;
import com.news.entity.SysDictValue;
import com.news.service.SysDictValueService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.validation.Errors;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 字典值表 前端控制器
 * </p>
 *
 * @author Janus
 * @since 2020-08-05
 */
@Api(tags = {"文件分类表"})
@Controller
@RequestMapping(value = {"/dict","/app/dict"})
public class SysDictValueController {

    private static Logger logger= LoggerFactory.getLogger(SysDictValueController.class);

//    @Autowired
//    SysDictService dictService;

    @Autowired
    SysDictValueService dictValueService;

    @RequestMapping("addPage")
    public String addPage(Model model){
        return "dictValue/add";
    }

    @RequestMapping("add")
    @ResponseBody
    public ResponseBean addDictValue(@Valid SysDictValue dictValue, Errors errors, HttpServletRequest request){
        logger.debug("addSysDictValue:"+dictValue);
        String dictValueCode = dictValue.getDictCode();
        if(StringUtils.isEmpty(dictValueCode)){
            logger.debug("编码为空！");
            return new ResponseBean(false, CommonEnum.BAD_REQUEST);
        }
        if(errors.getErrorCount() > 0){
            StringBuffer stringBuffer=new StringBuffer();
            for(FieldError error:errors.getFieldErrors()){
                stringBuffer.append(error.getField() + ":" + error.getDefaultMessage()+" ");
            }
            return ResultUtil.error(stringBuffer.toString());
        }
        QueryWrapper<SysDictValue> queryWrapper=new QueryWrapper();
        queryWrapper.eq("dict_code",dictValueCode).eq("dict_value",dictValue.getDictValue());
        List<SysDictValue> checkList = dictValueService.list(queryWrapper);
        if(ToolsUtils.isNotEmpty(checkList)){
            return  new ResponseBean(false,"字典code-value已经存在！");
        }
        boolean i = dictValueService.save(dictValue);
        logger.debug("保存后的dictValue:"+dictValue);
        return new ResponseBean<>(true, dictValue, CommonEnum.SUCCESS_REQUEST);
    }

    /**
     * 跳转到修改页面
     * @param id
     * @param model
     * @return
     */
    @RequestMapping("/editPage/{id}")
    public String editPage(@PathVariable Long id, Model model) {
        model.addAttribute("dictValue", dictValueService.getById(id));
        return "dictValue/edit";
    }


    /**
     * 修改
     * @param dictValue
     * @return
     */
    @RequestMapping("/edit")
    @ResponseBody
    public ResponseBean updateById(SysDictValue dictValue) {
        if (dictValue == null||dictValue.getId()==null) {
            return new ResponseBean(false, CommonEnum.BAD_REQUEST);
        }
        QueryWrapper<SysDictValue> queryWrapper=new QueryWrapper();
        queryWrapper.eq("dict_code",dictValue.getDictCode())
                .eq("dict_value",dictValue.getDictValue())
                .ne("id",dictValue.getId());
        List<SysDictValue> checkList=dictValueService.list(queryWrapper);
        if(ToolsUtils.isNotEmpty(checkList)){
            return new ResponseBean(false,"9999","字典code-value已经存在！");
        }
        boolean i = dictValueService.updateById(dictValue);
        return new ResponseBean(true,dictValue, CommonEnum.SUCCESS_OPTION);
    }

    /**
     * 跳转列表页面
     * @return
     */
    @RequestMapping("/listPage")
    public String dictValueListPage() {
        return "dictValue/list";
    }

    /**
     * 分页列表查询
     * @param pageNum 页码
     * @param pageSize 每页大小
     * @param queryParam 查询参数
     * @return
     */
    @RequestMapping("/list/{pageNum}/{pageSize}")
    @ResponseBody
    public ResponseBean getList(@PathVariable Integer pageNum, @PathVariable Integer pageSize,
                                SysDictValue queryParam, HttpSession session) {
        IPage<SysDictValue> indexPage = new Page<>(pageNum, pageSize);
        Map<String, Object> objectMap = ToolsUtils.convertObjToMap(queryParam);
        QueryWrapper<SysDictValue> queryWrapper=new QueryWrapper<>();
        queryWrapper.allEq(objectMap,false);
        IPage<SysDictValue> page = dictValueService.page(indexPage,queryWrapper);
        logger.debug("获取的字典值列表："+page);
        //获取分页信息
        Map<String, Object> pageInfo = new HashMap<String, Object>();
        pageInfo.put("pageSize", page.getSize());
        pageInfo.put("pageNum", page.getCurrent());
        pageInfo.put("pages", page.getPages());
        pageInfo.put("total", page.getTotal());
        Map<String, Object> resultMap = new HashMap<String, Object>();
        resultMap.put("dictValueList", page.getRecords());
        resultMap.put("pageInfo", pageInfo);
        return new ResponseBean<Map<String, Object>>(true, resultMap, CommonEnum.SUCCESS_REQUEST);
    }


    @ApiOperation(value="根据字典code查询字典值,诸如满减、平台都可以从该接口查询")
    @RequestMapping(value = "/queryValueByCode",method = RequestMethod.POST)
    @ResponseBody
    public ResponseBean queryValueByCode(String dictCode){
        QueryWrapper<SysDictValue> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("dict_code",dictCode);
        List<SysDictValue> list = dictValueService.list(queryWrapper);
        return new ResponseBean<>(true, list, CommonEnum.SUCCESS_OPTION);
    }

    @ApiOperation(value="根据ID删除字典值")
    @RequestMapping(value = "/delete/{id}",method = RequestMethod.POST)
    @ResponseBody
    public ResponseBean goodsDetlete(@PathVariable Long id){
        if(id==null||id<1){
            return ResultUtil.error("参数不正确！");
        }
        boolean b = dictValueService.removeById(id);
        return ResultUtil.success();
    }

    @RequestMapping(value = "deleteById",method = RequestMethod.POST)
    @ResponseBody
    public ResponseBean deleteById(Long id){
        if(id==null||id<1){
            return ResultUtil.error("参数不正确！");
        }
        boolean b = dictValueService.removeById(id);
        return ResultUtil.success();
    }

    @ApiOperation(value="根据ID批量删除字典值")
    @RequestMapping(value = "deleteBatchByIds",method = {RequestMethod.POST,RequestMethod.GET})
    @ResponseBody
    public ResponseBean deleteBatchByIds(@RequestParam List<Integer> idList){
        logger.debug("deleteBatchByIds:"+idList);
        if(idList==null||idList.isEmpty()){
            return  new ResponseBean(false,CommonEnum.BAD_REQUEST);
        }
        boolean delete = dictValueService.removeByIds(idList);
        logger.debug("批量删除结果："+delete);
        return new ResponseBean<Map<String, Object>>(true, null, CommonEnum.SUCCESS_REQUEST);
    }


}
